package cn.tedu.v3_1;

import java.io.*;
import java.net.*;
import java.util.*;

public class Client {
    private Socket socket;
    private String ip;
    private static final String HOST="172.20.17.9";
   private static final Integer PORT=6666;
   private PrintWriter pw;
   private BufferedReader br;
    public Client() {
        try {
            socket = new Socket(HOST, PORT);
             br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));

            pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);
        } catch (NullPointerException e){
            System.out.println("友情提示：IP传入错误导致连接失败");
        } catch (UnknownHostException e){
            System.out.println("友情提示：IP传入错误");
        } catch (ConnectException e){
            System.out.println("客户端连接失败：建议检查IP或者端口号");
        } catch (IOException e) {
            System.out.println("客户端连接服务器端失败，提示：检查IP/端口");
        }
    }
    public void start(){
        ip=socket.getInetAddress().getHostAddress();

        //    BufferedReader br=null;
        try {



            new Thread(()->{
                try {

                    String message;

                    while((message= br.readLine())!=null){
                        System.out.println("服务器端说："+message);
                        System.out.println("客户端请输入：");
                    }
                } catch (IOException e) {
                    System.out.println("服务器端读入失败");
                }
            }).start();

            Scanner input=new Scanner(System.in);
            while(true){
                System.out.println("客户端请输入：");
                String line= input.nextLine();
                pw.println(line);

            }
        }  finally {
            try {
                if (br!=null)
                    br.close();
            } catch (IOException e) {
                System.out.println("客户端关闭失败");
            }
            if(pw!=null)
                pw.close();
            if (socket != null && !socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {

                    System.out.println("服务器关闭失败");
                }
            }
        }
    }
    public static void main(String[] args){
        Client client=new Client();
        client.start();
    }
}